//
//  PerFocusAFansViewController.m
//  sklive
//
//  Created by Macx on 2017/5/24.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "PerFocusAFansViewController.h"
#import "FocusAndFansTableViewCell2.h"

#import "User.h"
#import "HomeServer.h"

// 私聊
#import "TCMsgHandler.h"

@interface PerFocusAFansViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) FocusAndFansTableViewCell2 *cell;
@property (nonatomic, strong) NSMutableArray *infoArr;

@property (nonatomic, assign) NSInteger page; // 网络请求页数

@property (nonatomic, strong) NSMutableArray *fansArr;

@property (nonatomic, strong) NSString *keyWord;

@property (nonatomic, assign) NSInteger isPush;

@end

@implementation PerFocusAFansViewController {
    
    UILabel     *_noThings;
}

- (void)viewWillAppear:(BOOL)animated {
    
    if (_vcType == 2) {
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchUser:)name:@"searchUser" object:nil];
        
    }
    
    if (self.vcType != 2 && self.page == 1) {
        // 获取关注or粉丝列表
        [self GETFocusAFans];
    }
    self.isPush = 0;
}

- (void)viewDidDisappear:(BOOL)animated {
    if (self.vcType == 2 && self.isPush == 0) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"searchUser" object:nil];
    }
}

// 主页tableView是否滚动接收到通知
- (void)searchUser:(NSNotification *)notification {
    self.keyWord = notification.userInfo[@"keyWord"];
    NSLog(@"－－－－－用户搜索接收到通知------\n = %@", self.keyWord);
    
//    _noThings.hidden = YES;
    [self GETFocusAFans];
}

//移除广播监听。
//-(void)dealloc{
//    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"searchUser" object:nil];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.keyWord = @"";
    
    // 进入请求为1
    self.page = 1;
    
    [self buildUI];
    
    [self refreshData];
    
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = kWhiteColor;
    
    if (self.vcType == 0) {
        self.navigationItem.title = @"我的粉丝";
    }
    else if (self.vcType == 1) {
        self.navigationItem.title = @"我的关注";
    }
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc]init];
    [self.tableView registerNib:[UINib nibWithNibName:@"FocusAndFansTableViewCell2" bundle:nil] forCellReuseIdentifier:@"cell"];
    
    if (self.vcType == 2) {
        self.tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64-(1+3*SW(20)));
    }
    
    _noThings = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-(65+SW(20)*3))];
    [self.view addSubview:_noThings];
    _noThings.text = @"没有相关资源";
    _noThings.textAlignment = NSTextAlignmentCenter;
    _noThings.backgroundColor = UISeparatedColorRGB;
    _noThings.hidden = YES;
    
}
#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETFocusAFans];
        
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETFocusAFans];
    }];
    
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    User *model = self.infoArr[indexPath.row];
    self.cell.model = model;
    
    self.cell.optionsBtn.tag = indexPath.row;
    [self.cell.optionsBtn addTarget:self action:@selector(fansAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return self.cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return SW(8)+20;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    User *model = self.infoArr[indexPath.row];
//    NSString *toId = [NSString stringWithFormat:@"%ld", model.user_id];
    
    IMAUser *user = [[IMAUser alloc] init];
    user.nickName = model.nickname;
    user.userId = [NSString stringWithFormat:@"%ld",model.user_id];
    user.remark = model.nickname;
    user.icon = model.face;
    
    #if kTestChatAttachment
        // 无则重新创建
        ChatViewController *chatVC= [[CustomChatUIViewController alloc] initWith:user];
    #else
    ChatViewController *chatVC = [[IMAChatViewController alloc] initWith:user];
    #endif
    
    self.isPush = 1;
    
    // 隐藏底部的buttomBar 当 push 的时候
    //        [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:chatVC animated:YES];
    
}

#pragma mark ==========响应方法==========
/**
 关注or粉丝
 */

- (void)GETFocusAFans {
    // GET /users/{uid}/favorites 获取关注的人 uid *关注人ID
    // GET /users/{uid}/fans 获取粉丝 uid *被关注人I
    
    NSString *url;
    NSDictionary *param;
    NSString *name;
    if (self.vcType == 1) {
        url = [NSString stringWithFormat:@"%@/%@/favorites", APIUser, self.userInfo[@"user_id"]];
        param = @{@"per_page":@"10", @"page":[NSString stringWithFormat:@"%ld", self.page]};
        name = @"获取关注";
    }
    else if (self.vcType == 0) {
        url = [NSString stringWithFormat:@"%@/%@/fans", APIUser, self.userInfo[@"user_id"]];
        param = @{@"per_page":@"10", @"page":[NSString stringWithFormat:@"%ld", self.page]};
        name = @"获取粉丝";
    }
    else if (self.vcType == 2) {
        if (self.keyWord.length == 0) {
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            return;
        }
        url = APIUserInfos;
        param = @{@"keyword":self.keyWord,
                  @"page":[NSString stringWithFormat:@"%ld", self.page],
                  @"per_page":@"10"};
        name = @"用户搜索";
    }
    
    
    [[NetworkTool sharedTool] requestWithName:name URLString:url parameters:param method:@"GET" callBack:^(id responseObject) {
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        _noThings.hidden = YES;
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
            // 所有的逻辑显示
            if (self.vcType == 2) {
                [_tableView.mj_footer endRefreshing];
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//                [LZCTools HUDMessage:@"没有这个用户" delay:1.5f];
                if (self.infoArr.count == 0) {
                    _noThings.hidden = NO;
                }
            }
        }
        for (NSDictionary *dic in arr) {
            User *model = [[User alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.infoArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
}

/**
 添加关注 or 取消关注
 */
- (void)fansAction:(UIButton *)sender {
    
    User *model = self.infoArr[sender.tag];
    NSString *toId = [model valueForKey:@"user_id"];
    
    [HomeServer focus:sender toId:toId];
}


// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}

- (NSMutableArray *)fansArr {
    if (_fansArr == nil) {
        _fansArr = [[NSMutableArray alloc] init];
    }
    return _fansArr;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
